package com.eco.fanliapp.service.impl;

import com.eco.fanliapp.dao.AppNewsLogMapper;
import com.eco.fanliapp.entity.AppNewsLog;
import com.eco.fanliapp.service.RedisLockService;
import com.eco.fanliapp.service.UpdateAppNewsLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UpdateAppNewsLogServiceImpl implements UpdateAppNewsLogService {
    @Autowired
    private AppNewsLogMapper appNewsLogMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisLockService redisLockService;

    @Override
    @Async
    public void toDatabase(long seconds) {
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<AppNewsLog> appNewsLogList = (List<AppNewsLog>)redisTemplate.opsForList().range("AllMessageToRead" + seconds, 0, -1);
        int i = 0;
        if (appNewsLogList !=null && appNewsLogList.size() > 0){
            i = appNewsLogMapper.allMessageToReadList(appNewsLogList);
        }
        //redis
        if(i > 0){
            redisTemplate.delete("AllMessageToRead" + seconds);
        }
    }

    @Override
    @Async
    public Integer inDatabase(long seconds) {
        if ( !redisLockService.lock("insertAppMessage_inDatabase_" + seconds, (System.currentTimeMillis() + 5000L) + "")) {
            return 0;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<AppNewsLog> appNewsLogList = (List<AppNewsLog>)redisTemplate.opsForList().range("InsertAppMessage" + seconds, 0, -1);
        Integer i = 0;
        if (appNewsLogList !=null && appNewsLogList.size() > 0){
            for(AppNewsLog appNewsLog:appNewsLogList){
                i = appNewsLogMapper.insertAppNewsLog(appNewsLog);
            }
        }
        //redis
//        if(i > 0){
            redisTemplate.delete("InsertAppMessage" + seconds);
//        }
        return i;
    }

}
